package top.whysu.edevice.service.manage.impl;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import top.whysu.edevice.constant.CodeConstant;
import top.whysu.edevice.constant.DataDictionary;
import top.whysu.edevice.dao.manage.ManageTreeDao;
import top.whysu.edevice.dto.manage.NodeAddDTO;
import top.whysu.edevice.dto.manage.NodeEditDTO;
import top.whysu.edevice.exception.BusinessException;
import top.whysu.edevice.po.manage.ManageTreePO;
import top.whysu.edevice.service.manage.ManageTreeService;
import top.whysu.edevice.service.system.AccountService;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 树结构
 */
@Service("ManageTreeServiceImpl")
public class ManageTreeServiceImpl implements ManageTreeService {

    private static Logger LOGGER = LoggerFactory.getLogger(ManageTreeServiceImpl.class);

    @Resource
    private ManageTreeDao manageTreeDao;
    @Resource
    private AccountService accountService;

    /**
     * 根据条件获取树结构列表
     */
    @Override
    public List<ManageTreePO> selectTreeNodeByCondition(Map<String, Object> params) {
        return manageTreeDao.selectTreeNodeByCondition(params);
    }


    @Override
    public synchronized BigDecimal wholeAddNode(NodeAddDTO nodeAddDTO) {
        Integer nodeType = nodeAddDTO.getNodeType();
        String nodeName = nodeAddDTO.getName();
        BigDecimal nodePid = nodeAddDTO.getPid();
        if (nodeType == null || StringUtils.isBlank(nodeName) || nodePid == null) {
            throw new BusinessException(CodeConstant.Http.PARAM_ERROR, "节点类型/节点名称/父节点id不能为空！");
        }
        // 如果是凭证组
        if (DataDictionary.NodeType.VOUCHER_TYPE == nodeType) {
            ManageTreePO queryPO = new ManageTreePO();
            queryPO.setType(DataDictionary.NodeType.VOUCHER_TYPE);
            queryPO.setName(nodeName);
            List<ManageTreePO> manageTreePOList = manageTreeDao.queryAll(queryPO);
            if (CollectionUtils.isNotEmpty(manageTreePOList)) {
                throw new BusinessException(CodeConstant.Http.NODE_EXIST, "该凭证组名称已被使用，请更改名称！");
            }
        }
        ManageTreePO manageTreePO = new ManageTreePO();
        manageTreePO.setType(nodeType);
        // 如果是凭证组,level是1，父id是0
        if (DataDictionary.NodeType.VOUCHER_TYPE == nodeType) {
            manageTreePO.setPid(new BigDecimal(0));
            manageTreePO.setLevel(1);
        } else {
            manageTreePO.setPid(nodePid);
            ManageTreePO parentTreePO = manageTreeDao.queryById(nodePid);
            if (parentTreePO == null) {
                throw new BusinessException(CodeConstant.Http.PARENT_NOT_EXIST, "父节点不存在，请刷新界面后重试！");
            }
            manageTreePO.setLevel(parentTreePO.getLevel() + 1);
        }
        // 根据节点获取icon
        manageTreePO.setIcon(getIcon(nodeType));
        manageTreePO.setName(nodeName);
        // 当前用户
        String currentUser = accountService.getCurrentLoginUser();
        manageTreePO.setCreateBy(currentUser);
        manageTreePO.setUpdateBy(currentUser);
        manageTreePO.setCreateTime(new Date());
        manageTreePO.setUpdateTime(new Date());
        manageTreeDao.insert(manageTreePO);
        return manageTreePO.getId();
    }

    @Override
    public synchronized void wholeModifyNode(NodeEditDTO nodeEditDTO) {
        BigDecimal treeId = nodeEditDTO.getId();
        String newNodeName = nodeEditDTO.getName();
        if (treeId == null || StringUtils.isBlank(newNodeName)) {
            throw new BusinessException(CodeConstant.Http.INFO_ERROR, "节点id/节点名称不能为空！");
        }
        ManageTreePO manageTreePO = new ManageTreePO();
        manageTreePO.setId(treeId);
        manageTreePO.setName(newNodeName);
        manageTreePO.setUpdateTime(new Date());
        manageTreePO.setUpdateBy(accountService.getCurrentLoginUser());
        manageTreeDao.update(manageTreePO);
    }

    @Override
    public void wholeDeleteNode(BigDecimal id) {
        if (id == null) {
            throw new BusinessException(CodeConstant.Http.PARAM_ERROR, "id不能为空！");
        }
        // 查询是否还有子节点
        List<ManageTreePO> treePOList = selectChildListByPid(id);
        if (CollectionUtils.isNotEmpty(treePOList)) {
            throw new BusinessException(CodeConstant.Http.EXECUTE_FAIL, "当前节点下还有子节点，不允许删除！");
        }
        // 如果是凭证组的话，不允许在这里删除
        ManageTreePO manageTreePO = manageTreeDao.queryById(id);
        if (manageTreePO != null && DataDictionary.NodeType.VOUCHER_TYPE == manageTreePO.getType()) {
            throw new BusinessException(CodeConstant.Http.EXECUTE_FAIL, "不允许在树结构上删除凭证组！");
        }
        // 删除节点
        manageTreeDao.deleteById(id);
    }

    /**
     * 根据pid查询子节点集合
     */
    private List<ManageTreePO> selectChildListByPid(BigDecimal pid) {
        ManageTreePO queryPO = new ManageTreePO();
        queryPO.setPid(pid);
        return manageTreeDao.queryAll(queryPO);
    }

    /**
     * 根据节点类型获取icon
     */
    private String getIcon(Integer nodeType) {
        if (DataDictionary.NodeType.VOUCHER_TYPE == nodeType) {
            return DataDictionary.Icon.VOUCHER;
        } else if (DataDictionary.NodeType.SITE_TYPE == nodeType) {
            return DataDictionary.Icon.SITE;
        } else if (DataDictionary.NodeType.DEVICE_TYPE == nodeType) {
            return DataDictionary.Icon.DEVICE;
        } else {
            throw new BusinessException(CodeConstant.Http.EXECUTE_FAIL, "节点类型不支持");
        }
    }
}